package com.tanhua.dubbo.server.service;

import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.pojo.Users;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class TimeLineService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Async
    public  CompletableFuture<String> saveTimeLine(Long userId, ObjectId publishId) {
        try {
            Query query = Query.query(Criteria.where("userId").is(userId));
            List<Users> usersList = this.mongoTemplate.find(query, Users.class);

            TimeLine timeLine = new TimeLine();
            timeLine.setDate(System.currentTimeMillis());
            timeLine.setId(ObjectId.get());
            timeLine.setPublishId(publishId);
            timeLine.setUserId(userId);

            for (Users users : usersList) {
                this.mongoTemplate.save(timeLine,"quanzi_time_line_" + users.getFriendId());
            }
        } catch (Exception e) {
            System.out.println("dsadadsa");
            System.out.println("dsadadsa");
            log.error("写入好友时间线表失败~ userId = " + userId + ", publishId = " + publishId, e);
        }
        return CompletableFuture.completedFuture("ok");
    }
}
